﻿
var actionUrl = '/Dev/ashx/DevConfigHandler.ashx';
var devtype = [{ "id": "CBD", "text": "测报灯", "selected": true }, { "id": "YBQ", "text": "靶标害虫设备" }, { "id": "XQH", "text": "小气候气象仪" }, { "id": "PIC", "text": "图像监测" }, { "id": "PICSB", "text": "图像识别" }, { "id": "MQ_QJ", "text": "摄像头" }, { "id": "BZP", "text": "孢子识别" }];
var weathertype = [{ "id": "土壤温度", "text": "土壤温度" }, { "id": "土壤湿度", "text": "土壤湿度" }, { "id": "空气温度", "text": "空气温度" }, { "id": "空气湿度", "text": "空气湿度" }, { "id": "光照", "text": "光照" }, { "id": "大气压力", "text": "大气压力" }, { "id": "风速", "text": "风速" }, { "id": "风向", "text": "风向" }, { "id": "净辐射", "text": "净辐射" }, { "id": "太阳辐射", "text": "太阳辐射" }, { "id": "紫外辐射", "text": "紫外辐射" }, { "id": "蒸发", "text": "蒸发" }, { "id": "二氧化碳", "text": "二氧化碳" }, { "id": "雨量", "text": "雨量" }, { "id": "蒸发量", "text": "蒸发量" }, { "id": "PM2_5", "text": "PM2_5" }, { "id": "PM10", "text": "PM10" }];

function Travel(text) {
    var arr = text.split(',');
    for (i = 0; i < arr.length ; i++) {
        var roots = $('#XQHID').tree('getRoots');
        for (i = 0; i < roots.length; i++) {            
            children = $('#' + treeID).tree('getChildren', roots[i].target);
            for (j = 0; j < children.length; j++) alert(children[j].text);
        }
        node = $('#XQHID').combotree('tree').tree('find', arr[i]);
        $('#XQHID').combotree('tree').tree('check', node.target);
        //$('#XQHID').combotree('tree').tree('expandAll', node.target);
    }
}

$(function () {
    var size = { width: $(window).width(), height: $(window).height() };
    mylayout.init(size);
    $(window).resize(function () {
        size = { width: $(window).width(), height: $(window).height() };
        mylayout.resize(size);
    });
    //mygrid.databind(size);
    DicCategory.bindTree();
    autoResize({ dataGrid: '#userGrid', gridType: 'datagrid', callback: mygrid.databind, height: 4, width: 204 });

    //字典数据
    
       
    $('#a_add').click(mygrid.add);
    $('#a_edit').click(mygrid.edit);
    $('#a_delete').click(mygrid.del);
    $('#a_refresh').click(function () {
        var sname = DicCategory.getSelected();
        if (node)
            mygrid.reload(node.id);
        else {
            msg.warning('请选择字典类别。');
        }
    });
    $('#a_search').click(function () {
        var sname = $("#txt_search").val();
        $('#userList').tree({
            url: '/Dev/ashx/DevConfigHandler.ashx?action=names&searcht='+sname,
            onLoadSuccess: function (node, data) {
                if (data.length == 0) {
                    $('#noCategoryInfo').fadeIn();
                }

                $('body').data('categoryData', data);
            }
        });
    });
});

var mylayout = {
    init: function (size) {
        $('#layout').width(size.width - 4).height(size.height - 4).layout();
        var center = $('#layout').layout('panel', 'center');
        var west = $('#layout').layout('panel', 'west');
        center.panel({
            onResize: function (w, h) {
                $('#dicGrid').datagrid('resize', { width: w, height: h });
                $('#userList').tree({ height: h - 80 });
            }
        });       
    },
    resize: function (size) {
        mylayout.init(size);
        $('#layout').layout('resize');
    }
};

var DicCategory = {
    bindTree: function () {
        $('#userList').tree({
            url: '/Dev/ashx/DevConfigHandler.ashx?action=names',
            onLoadSuccess: function (node, data) {
                if (data.length == 0) {
                    $('#noCategoryInfo').fadeIn();
                }
                $('body').data('categoryData', data);
                mygrid.reload();
            },
            onClick: function (node) {
                var cc = node.id;
                $('body').data('uid',cc);
                var mm = node.attributes.mobile;
                $('#dicGrid').treegrid({
                    title: "[" + node.attributes.username + "] 的设备列表",
                    url: actionUrl,
                    queryParams: { categoryId: cc, mobile: mm }
                });
            }
        });
    },
    reload: function () {
        $('#userList').tree('reload');
    },
    getSelected: function () {
        return $('#userList').tree('getSelected');
    }
};

function createParam(action, keyid) {
    var o = {};
    var query = top.$('#devForm').serializeArray();
    query = convertArray(query);
    o.jsonEntity = JSON.stringify(query);
    o.action = action;
    o.keyid = keyid;    
    return "json=" + JSON.stringify(o);
}

var dicDialog;
var mygrid = {
    databind: function (winSize) {
        $('#dicGrid').treegrid({
            toolbar: '#toolbar',
            title: "此用户的设备列表",
            iconCls: 'icon icon-list',
            width: winSize.width,
            height: winSize.height,
            nowrap: false, //折行
            rownumbers: true, //行号
            striped: true, //隔行变色
            idField: 'KeyId', //主键
            singleSelect: true, //单选
            frozenColumns: [[]],
            columns: [[
                
                { title: '设备类型', field: 'DevType', width: 60 },
                { title: '设备编码', field: 'DevID', width: 80 },
                { title: '测报点名称', field: 'DevOwnerName', width: 100 },
                { title: '设备相关属性', field: 'XQHID', width: 100 },
                { title: '设备地址', field: 'DevLocation', width: 180 },
                {
                    title: '通道', field: 'chs', width: 100, formatter: function (v, d, i) {
                        if (v == ",,,")
                            return "";
                        else
                            return v;
                    }
                },
                { title: '设备卡号/备注', field: 'DevContact', width: 100 },
                {
                    title: '操作', field: 'op', width: 50,
                    formatter: function (v, d, i) {
                        if (d.DevType == "YBQ")
                            return '<img style="cursor:pointer" title="设置小气候" onclick="javascript:setDevAttr(' + d.KeyId + ',' + d.DevOwnerID + ')" src="/css/icon/16/weather_cloudy_rain.png" />';
                       
                    }
                }
            ]],
            pagination:false,
            pageSize: PAGESIZE,
            pageList: [20, 40, 50]
        });
    },
    reload: function () {
        var uid = $('body').data('uid');
        $('#dicGrid').treegrid({
            url: actionUrl,
            queryParams: { categoryId: uid }
        });
    },
    GetSelectedRow: function () {
        return $('#dicGrid').treegrid('getSelected');
    },
    initCtrl: function (dicId) {
        if (DicCategory.getSelected())
        top.$('#DevOwnerID').val(DicCategory.getSelected().id);
        top.$('#DevType').combobox({
            data: devtype, width: 120, valueField: 'id', textField: 'text', editable: false, panelHeight: 'auto',
            onChange: function (n, o) {
                if (n == "YBQ") {
                    top.$(".mych").show();
                }
                else {
                    top.$(".mych").hide();
                }
                if (n == "XQH") {
                    top.$(".myxqh").show();
                    top.$('#XQHID').combobox({
                        data: weathertype, valueField: 'id', textField: 'text', panelHeight: 'auto', checkbox: true, width: 200, multiple: true
                       
                    });
                }
                else {
                    top.$(".myxqh").hide();
                }

            }
        });
    },
    add: function () {

        if (!DicCategory.getSelected()) {
            msg.warning('亲，请选择某个用户！');
            return false;
        }
        dicDialog = top.$.hDialog({
            href: '/Dev/html/form.html',
            width: 400,
            height: 400,
            title: '新建设备',
            iconCls: 'icon-add',
            onLoad: function () {
                mygrid.initCtrl();
            },
            submit: function () {
                var query = createParam("add", 0);
                if (top.$('#devForm').form('validate')) {
                    $.ajaxjson(actionUrl, 'action=add&' + top.$('#devForm').serialize(), function (d) {
                        if (d.Data > 0) {
                            msg.ok(d.Message);
                            mygrid.reload();//top.$('#DevOwnerID').combobox('getValue')
                            dicDialog.dialog('close');
                        } else {
                            MessageOrRedirect(d);
                        }
                    });
                }
            }
        });
    },
    edit: function () {
        var row = mygrid.GetSelectedRow();
        if (row) {
            var editDialog = top.$.hDialog({
                href: '/Dev/html/form.html?v=' + Math.random(),
                width: 500,
                height: 350,
                title: '修改设备',
                iconCls: 'icon-edit',
                onLoad: function () {
                    mygrid.initCtrl();
                    var viewModel = top.ko.mapping.fromJS(row);
                    top.ko.applyBindings(viewModel);
                    top.$('#DevType').combobox('setValue', row.DevType);
                   
                    if (row.DevType == "YBQ") {
                        top.$(".mych").show();
                    }
                    else {
                        top.$(".mych").hide();
                    }
                    if (row.DevType == "XQH") {
                        top.$(".myxqh").show();
                        top.$('#XQHID').combobox({
                            data: weathertype, valueField: 'id', textField: 'text', panelHeight: 'auto', checkbox: true, width: 200, multiple: true

                        });
                        top.$('#XQHID').combobox('setValues', eval('[' + "'" + row.XQHID.replace(/,/g, "','") + "'" + ']'));
                    }
                    else {
                        top.$(".myxqh").hide();
                    }
                    //Travel(row.XQHID);
                    
                    //top.$('#XQHID').combobox('setValues',  row.XQHID );
                },
                submit: function () {
                    if (top.$('#devForm').form('validate')) {
                        var query = createParam('edit', row.KeyId);
                        $.ajaxjson(actionUrl, query, function (d) {
                            if (d.Success) {
                                msg.ok('修改成功');
                                mygrid.reload();
                                editDialog.dialog('close');
                            }
                            else {
                                if (d.Data == -1) {
                                    msg.error('修改失败！');                                    
                                } 
                            }
                        });
                    }
                    //else {
                    //    msg.warning('数据不合理。');
                    //}
                }
            });
        } else {
            msg.warning('请选择要修改的设备。');
        }
    },
    del: function () {
        var row = mygrid.GetSelectedRow();
        if (row) {
            var query = createParam('del', row.KeyId);
            top.$.messager.confirm('删除设备', '确认要删除选中的设备吗?', function (r) {
                if (r) {
                    $.ajaxjson(actionUrl+"?devtype="+row.DevType+"&devid="+row.DevID, query, function (d) {
                        if (d.Success) {
                            msg.ok('删除成功');
                            mygrid.reload();
                        } else {
                            if (d.Data == -2)
                                msg.error('admin为系统帐号，不能删除。');
                            else {
                                MessageOrRedirect(d);
                            }
                        }
                    });
                }
            });           
        } else {
            msg.warning('请选中要删除的设备数据。');
        }
    }
}

function setDevAttr(keyid, uid) {
    
  var  devDialog = top.$.hDialog({
        href: '/Dev/html/setdev.html',
        width: 300,
        height: 150,
        title: '设置小气候',
        iconCls: 'icon-add',
        onLoad: function () {
            //初始化自己的设备
            top.$('#keyid').val(keyid);
            $.getJSON(actionUrl + '?uid=' + uid + '&' + createParam('getmy') + '&r=' + Math.floor(Math.random() * (1000 + 1)), function (d) {
                top.$('#DevType').combobox({ data: d, width: 120, valueField: 'DevContact', textField: 'DevContact', editable: false, panelHeight: 'auto' });
                $.getJSON(actionUrl + '?keyid=' + keyid + '&' + createParam('getmydevxqh') + '&r=' + Math.floor(Math.random() * (1000 + 1)), function (d) {
                    if(d.length==1 && d[0].XQHID!="")
                    top.$('#DevType').combobox('setValue', d[0].XQHID);                   
                });                
            });
        },
        submit: function () {            
            if (top.$('#setdevForm').form('validate')) {
                $.ajaxjson(actionUrl, 'action=setdev&' + top.$('#setdevForm').serialize(), function (d) {
                    if (d.Data > 0) {
                        msg.ok(d.Message);                        
                        devDialog.dialog('close');
                        mygrid.reload();
                    } else {
                        msg.ok(d.Message);
                    }
                });
            }
        }
    });
}